import { Component, OnInit } from '@angular/core';
import { LocalStorage } from '@core/local.storage';
import { ApiService } from '../../../../core/api.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup, AbstractControl } from '@angular/forms';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-kkbj',
    templateUrl: './kkbj.component.html',
    styleUrls: ['./kkbj.component.less']
})

export class KkbjComponent implements OnInit {

    userInfo = JSON.parse(this.ls.get('loginInfo'));
    dateFormat = 'yyyy/MM/dd HH:mm:ss';
    validateForm: FormGroup;
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
    isMainPage = true;
    lastNode: any;
    checkStatus = [];
    data = {
        tableData: [],
        tableTotal: 0,
        tablePagination: {
            page: 1,
            rows: 10,
        },
        ctrlNames: {
            bm: 'bm',
            fzr: 'fzr',
            sjStart: 'sjStart',
            sjEnd: 'sjEnd',
        },
        nodes: [],
        bjtj: { allalert: 0, ckalert: 0 },
    };



    constructor(public ls: LocalStorage,
        private apiService: ApiService,
        private message: NzMessageService,
        private formBuilder: FormBuilder,
        private modalService: NzModalService,
        private datePipe: DatePipe
    ) { }

    ngOnInit() {
        this.validateForm = this.formBuilder.group({});
        this._addControls();
        this.getBm();
        this.getBjTj();
        this.query();
    }

    _addControls() {
        const values = Object.values(this.data.ctrlNames);
        values.forEach(el => {
            this.validateForm.addControl(el, new FormControl());
        });
    }

    stringEqual(obj1: object, obj2: object) {
        const str1 = JSON.stringify(obj1);
        const str2 = JSON.stringify(obj2);
        return str1 == str2;
    }

    getBm() {
        this.apiService.gjqdgl_dispatcher(
            'sxdgl_bm', {}, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.nodes = _data.filter(el => el.children);
            this.data.nodes.unshift({
                title: '全部',
                // key: '',
                // children:[]
            });
        });
    }

    /**
     *
           taskname	任务名称
            shopName	车间
            areaName	工区
            toolsamountwrongreason	遗失清单
            name 	工具检查负责人
            beforeworkscandatetime	工具下道时间
            afterworkscandatetime	工具上道时间
            remark	备注
     */
    query(reset: boolean = false) {
        if (reset == true || this.data.tablePagination.page == 0) {
            this.data.tablePagination.page = 1;
        }
        const vfv = this.validateForm.value;
        const ctrlNames = this.data.ctrlNames;
        const param: any = {};
        if (this.lastNode && this.lastNode.key) {
            if (this.lastNode.children) {
                param.shopName = this.lastNode.key || '';
            } else {
                param.areaName = this.lastNode.key || '';
            }
        }
        param.name = vfv[ctrlNames.fzr] || '';
        param.beforeworkscandatetime = this.datePipe.transform(vfv[ctrlNames.sjStart], 'yyyy-MM-dd') || '';
        param.afterworkscandatetime = this.datePipe.transform(vfv[ctrlNames.sjEnd], 'yyyy-MM-dd') || '';
        if (param.afterworkscandatetime) {
            param.afterworkscandatetime += ' 23:59:59';
        }
        param.page = this.data.tablePagination.page;
        param.rows = this.data.tablePagination.rows;
        this.apiService.gjqdgl_dispatcher(
            'kkbj_table', param, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.tableTotal = _data.totalCount;
            this.data.tableData = _data.data;
            if (_data.data) {
                this.checkStatus = new Array(_data.data.length);
                this.checkStatus.fill(false, 0, _data.data.length);
            }
        });
    }

    nzTreeClick($e: any): void {
        this.lastNode = $e.node;
    }

    nzPageIndexChange() {
        if (this.data.tablePagination.page == 0) {
            return;
        }
        this.query();
    }

    setPageSize() {

        this.query(true);

    }

    shenHe_all() {
        // let checkedItem = [];
        let tasks = '';
        const taskids = [];
        const taskNames = [];
        for (let index = 0; index < this.checkStatus.length; index++) {
            const checked = this.checkStatus[index];
            if (checked) {
                const taskid = this.data.tableData[index].taskid;
                const taskname = this.data.tableData[index].taskname;
                // checkedItem.push([
                //     taskid,
                //     taskname
                // ]);
                taskNames.push(taskname);
                tasks += taskname + '<br>';
                taskids.push(taskid);
            }
        }

        // this.shenHe(taskid, taskname);
        this.modalService.confirm({
            nzTitle: '<i>确认审核以下项目吗</i>',
            nzContent: `<b>${tasks}</b>`,
            nzOnOk: () => {
                this.shenHe(taskids);
            }
        });

        // let func = function(a,b){}
        // let arr = [1,2];
        // func(...arr);
    }

    getObs(taskids) {
        const obs = [];
        taskids.forEach(el => {
            const ob = this.apiService.gjqdgl_dispatcher(
                'kkbj_sh', { taskId: el }, 'save', 'post'
            );
            obs.push(ob);
        });
        return obs;
    }

    shenHe(taskids) {
        if (!taskids) {
            return;
        }
        this.apiService.gjqdgl_dispatcher(
            'kkbj_sh', { taskId: taskids.join(',') }, 'save', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            if (_data.code == 'success') {
                this.message.create('success', '审核成功');
            } else {
                this.message.create('error', '审核失败');
            }
            this.query(false);
        });
    }

    getBjTj() {
        this.apiService.gjqdgl_dispatcher(
            'gjqdgl_bjtj', {}, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.bjtj = _data.data;
        });
    }

}
